// $Id: jt.cpp 12 2009-05-04 19:51:42Z longerdev $

/*
Copyright (C) 2008 Longer <longerdev@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "jt.h"
#include "confpath.h"

JT::JT(){
	openlog("jt", LOG_CONS | LOG_PID, LOG_DAEMON);	
	if (conf.load(SYSCONFDIR"/jt.conf") == -1){
		syslog(LOG_ERR, "jt.conf not exist!");
		std::cerr << "jt.conf not exist!" << std::endl;
		exit(EXIT_FAILURE);
	}

	imDaemon = false;
}

JT::~JT(){
	if (imDaemon){
		syslog(LOG_INFO, "JT close");
		unlink(pid_path.c_str());
	}
	closelog();
}

int JT::wr_pid(){
	FILE * fd;
	pid_t mypid;

	fd = fopen(pid_path.c_str(), "wt");
	
	mypid = getpid();
	fwrite(&mypid, sizeof(pid_t), 1, fd);

	fclose(fd);

	return 0;
}

/*
pid_t JT::r_pid(){
	FILE * fd;
	pid_t mypid;

	fd = fopen(pid_path.c_str(), "rt");
	if (fd){
		fread(&mypid, sizeof(pid_t), 1, fd);
		fclose(fd);
	}
	else{
		// ERROR
		std::cerr << "pid file deleted..." << std::endl;
		exit(EXIT_FAILURE);
	}

	return mypid;
}
*/

int JT::is_lock(){
	FILE * fd;

	fd = fopen(pid_path.c_str(), "r");
	if (fd){
		fclose(fd);
		return 1;
	}

	return 0;
}

void JT::init(const std::string sName){
	pid_path = conf.getValue("global::pid_path") + "jt_" + sName + ".pid";

	if (is_lock()){
		std::cerr << pid_path << " is exist." << std::endl;
		exit(EXIT_FAILURE);
	}

	int pid;
	pid = fork();

	switch (pid){
		case 0:{
			setsid();
			daemon(1, 1);

			imDaemon = true;

			syslog(LOG_INFO, "Start  JT [%s]", sName.c_str());

			wr_pid();

			JabCon b;
			if (conf.isKey(sName + "::server"))
				b.setServer(conf.getValue(sName + "::server"));
			if (conf.isKey(sName + "::port"))
				b.setPort(atoi(conf.getValue(sName + "::port").c_str()));

			b.setAuthData(conf.getValue(sName + "::jid"), conf.getValue(sName + "::pass"));
			b.setJIDs(conf.getValue(sName + "::myjid"), conf.getValue(sName + "::descjid"));
			while (1){
				b.JConnect();
				if (!b.isExit){
					syslog(LOG_NOTICE, "Disconnect JT [%s]", sName.c_str());
					sleep(10);
				}
				else
					break;
			}
		}
		break;

		case -1:
			std::cout << "Error: Don't start daemon :(" << std::endl;
			break;

		default:
			std::cout << "Start " << sName << std::endl;
			break;
	}

	return;
}


